/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

#include "TypeMeta.h"

#include "MetaEncoding.h"

#include "../common/U8ascii.h"

type_name meta_encoding_name = { "meta.encoding" };

static int meta_encoding_bind( type_element * element, type_definition * definition )
{
	meta_encoding * me = (meta_encoding *) element;
	int rc;
	
	rc = type_object_bind( &element->object, definition->library, &meta_encoding_name );
	if ( rc != TYPE_OK ) return rc;

	rc = type_element_bind( element, definition );
	if ( rc != TYPE_OK ) return rc;

	rc = me->data->element.bind( &(me->data->element), definition );
	if ( rc != TYPE_OK ) return rc;
	
	return TYPE_OK;
}

void meta_encoding_init( meta_encoding * me, meta_expression * data, char * type )
{
	type_element_init( &(me->expression.element), &meta_encoding_bind );
	meta_expression_init( &(me->expression), meta_encoding_do_read, meta_encoding_do_write );

	me->data = data;
	me->type = type;
}

void * meta_encoding_construct( type_list * list, type_map * map )
{
	type_item * item = type_list_head( list );
	meta_expression * data = (meta_expression *) type_item_get_ptr( item );	
	item = type_item_next( item );
	
	/* FIX ME A BIT OF A HACK. BAD META DICTIONARY */
	char * type = ((type_name *) type_item_get_ptr( item ))->name;
	
	meta_encoding * me = (meta_encoding*) type_malloc( sizeof( meta_encoding ) );
	meta_encoding_init( me, data, type );
	return me;
}

int meta_encoding_read( type_input_stream * in, type_element * element )
{
	return type_reader_auto( in, element, meta_encoding_construct );
}

int meta_encoding_write( type_output_stream * out, void * o, type_element * element )
{
	meta_encoding * enc = (meta_encoding *) o;
	int rc;

	rc = type_output_write_named_object( out, &meta_expression_name, enc->data );	
	if ( rc != TYPE_OK ) return rc;
	
	/* FIX ME should not meta.name is wrong here */
	/*return type_output_write_named_object( out, &meta_name_name, enc->type );	*/	
	return u8ascii_write( out, enc->type, NULL );	
}

int meta_encoding_do_read( type_input_stream * in, type_element * element )
{
	/* TODO FIX ME */
	return TYPE_EOF;
}

int meta_encoding_do_write( type_output_stream * out, void * o, type_element * element )
{
	/* TODO FIXME */
	return TYPE_EOF;	
}
